let _Vue = null;
export default class VueRouter {
   
    static install(Vue){
        // 1. 判断当前插件是否被安装
        if(VueRouter.install.isInstalled){
            return
        }
        VueRouter.install.isInstalled = true
        // 2. 把vue 构造函数记录到全局变量
        _Vue=Vue 
        // 3. 把Vue实例上增加router对象,以供组件和页面访问
        // _Vue.prototype.$router = this.$options.$router //this指向 为VueRouter 应该是Vue实例,使用混入
        _Vue.mixin({
            beforeCreate() {
                // 页面就绑定.组件就不绑定
                if(this.$options.router){
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            },
        })
    }
    constructor(options){
        this.options=options;
        // 存储路由规则
        this.routeMap={};
        // 响应式对象 以供访问当前路由
        this.data= _Vue.observable({
            current:'/',
            isHistory:options.mode==='history'
        })
        // /#/about
    }

    createRouteMap(){
        // 遍历所有路由规则.存储到routeMAP中
        this.options.routes.forEach(route=>{
            this.routeMap[route.path]=route.component
        })
    }
    init(){
        this.createRouteMap();
        this.initComponents(_Vue);
        this.initEvent();

    }
    initComponents(Vue){
        Vue.component('router-link',{
            props:{
                to:String
            },
            render(h){
                return h('a',{
                    attrs:{
                        href:'/#'+this.to
                    },
                    on:{
                        click:this.clickHandler
                    }
                },[this.$slots.default])
            },
            methods:{
                clickHandler(e){
                    e.preventDefault();

                    // history.pushState({},'',this.to)
                    let url =this.$router.data.isHistory?this.to:'/#'+this.to;
                    history.pushState({},'',url)
                    this.$router.data.current=this.to
                }
            }
            // template:'<a :href="to"><slot></slot></a>'
        })
        const that = this;
        Vue.component('router-view',{
            render(h){
                const component = that.routeMap[that.data.current]
                return h(component)
            }
        })
    }
    initEvent(){
        console.log(this.data)
        if(this.data.isHistory){
            window.addEventListener('popstate',()=>{
                this.data.current=window.location.pathname
                console.log(window.location.pathname)
            })
        }else{
            window.addEventListener('hashchange',()=>{
                // console.log(window.location.hash.replace(/^#\//,''))
                this.data.current=window.location.hash.replace(/^#/,'')
            })
        }
        
    }
}